<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>购物车</title>
<link href="${pageContext.request.contextPath}/shopcar/css/shopcart.css" rel="stylesheet" type="text/css" />
<link href="${pageContext.request.contextPath}/shopcar/css/page.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/shopcar/js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/shopcar/js/page.js"></script>


<style type="text/css">
.page-input{
	width:40px;
	height: 20px;
	line-height: 20px;
	padding-left: 5px;
	border-radius: 5px;
	border:1px solid #ccc;
	outline: none;
}
.page-btn{
	width:40px;
	height: 28px;
	line-height: 20px;
	padding-left: 5px;
	border-radius: 5px;
	border: none;
	color:#fff;
	background: #6CB98F;
}
</style>

<script type="text/javascript">
	var strjson;//结算按钮触发
	var carobj;//接收查询传过来的数据！
	var txtOldVal;
	var goodsNum;
	function getOldNum(txtObj,goodsnum){
	 	txtOldVal=txtObj;
	 	goodsNum=goodsnum;
	}
	
	function modifyNum(txtObj){
       var carid= txtObj.id;  //购物车编号
       var newNum= txtObj.value;  //修改后的购买数量   
       if(newNum<=0){
          if(confirm("您确定是您要购买的该项商品数量吗?")){
           alert("您购买商品数量不对！！");
          }else{
      	   	 txtObj.value=txtOldVal;
      	   }
       }
      else{ 
   
         	if(newNum>goodsNum){
         	
         	  window.confirm("库存量不足！无法进行货物交易"); 
         	 // newNum=txtOldVal;
         	 $(function(){
         	      $.ajax({
         	        type:'post',
         	        url:'${pageContext.request.contextPath}/shopNum',
         	        data:{
         	          num:txtOldVal,
         	        },
         	        success:function(response,status,xhr){
         	    // alert(response);
         	      $(".shopnum").val(response);
         	       } 
         	      });
         	 });
         	 
         	 	 
         	}
         	else {
         	  if(newNum!=txtOldVal){
      	  	//修改购物车中商品购买数量
      	   	var url="${pageContext.request.contextPath}/updateCarInfoServlet";
      	  	url+="?carId="+carid;
      	  	url+="&newNum="+newNum;
         	window.location.href= url;
      	  }
	  } 
	}
}
   //结算按钮触发
   function payMoney(){
	   var stu = eval('(' + strjson + ')');
	   //ajax 多购物车ID操作！    
        $.ajax({
            type:'POST',
            url:'${pageContext.request.contextPath}/product.action?method=queryByUserIdPage',
            data:stu,
            success:function(response,status,xhr){ 
            	if(response==1){
            		//结算失败
            		alert("系统错误，结算失败！");
                }else{
                	//登录成功
          			window.location="${pageContext.request.contextPath}/product.action?method=queryByUserId";
                	
                }
            }
        });
	   
	}
	
    //第一次json数据转换！
	carobj = ${carjson};

   //单选按钮触发事件！	
   function checkBoxWang(obj){
		caculateMoney();
   }

	
  function caculateMoney(){
  	
  	 //一页分几条数据
  	 //var page = 5;
  	 var carsid = new Array();
	 var num=0;
	 var totalCash=0.0;
	 var carJson = "{";
	   //单选按钮触发！
	   $("#mydata input[type='checkbox']").each(function(){
			//数据
			if($(this).is(":checked")){
			  totalCash+=(carobj[$(this).val()].goodsPrice)*(carobj[$(this).val()].shopNum);
			  carsid[$(this).val()]=${carjson}[$(this).val()].carId;
			  num++; 		
	        }else{
	        	carsid[$(this).val()]=0;
	        }
			
	        if(totalCash!=0){
	         $("#jz1").css("display", "none");
			 $("#jz2").css("display", "block");
	        }else{
	          //未选中不能结算样式！
	          $("#jz1").css("display", "block");
			  $("#jz2").css("display", "none");
	        }
	     document.getElementById("shuliang").innerHTML=num; 
	     document.getElementById("sumprice").innerHTML=totalCash;
	        
	  }); 
	  
	    
	    //搭建 json 格式
		for(var i=0;i<carsid.length;i++){
			carJson+='"'+i+'":'+carsid[i]+',';
			
		}
		
		strjson = carJson.substring(0,carJson.lastIndexOf(','));
		strjson+="}";
   }
      
   $(function(){
     	/*/选中单个checkbox
		$("#mydata input[type='checkbox']").click(function(){
			alert(140);
			caculateMoney();          
   		});*/

	//checkbox 全选反选
	$("#allselect").click(function(){
		var t = $("#mydata input[type='checkbox']");
		if($(this).is(":checked")){
			t.prop("checked",true);
			caculateMoney();
		}else{
			t.prop("checked",false);
			caculateMoney();
		}
	});
   });
	

   function removeById(no){
        if(window.confirm("您确定要删除吗?")){
           window.location.href="product.action?method=deleteCartById&no="+no;
        }
   }
       
   function clearChart(){
      if(window.confirm("您确定要清空购物车吗?")){
       window.location.href="product.action?method=deleteCart";
      }
   }    
 
</script>

</head>
<body>

<jsp:include page="top.jsp"/>
<div class="gwc" style=" margin:auto;">
	<table cellpadding="0" cellspacing="0" class="gwc_tb1" >
		<tr>
			<td class="tb1_td1"><input id="allselect" type="checkbox"  class="allselect"/></td>
			<td class="tb1_td1">全选</td>
			<td class="tb1_td3">商品</td>
			<td class="tb1_td4">商品信息</td>
			<td class="tb1_td5">数量</td>
			<td class="tb1_td5">单价</td>
			<td class="tb1_td6">小计</td>
			<td class="tb1_td7">操作</td>
		</tr>	
	</table>
	
	<table cellpadding="0" cellspacing="0" class="gwc_tb2" id="mydata" border="5" >
	<c:forEach items="${car}" var="carinfo"  varStatus="c">
		<tr bgcolor="${c.index%2==0?'white':'skyblue' }">
		   <td class="tb2_td1" colspan="2"><input type="checkbox" name="checkbox" value="${c.index }" onclick="checkBoxWang(this);"></td>
		   <td class="tb2_td2" class=".tb2_td2 img"><img style="width:60px;heigth:10px;" src="${pageContext.request.contextPath}/${carinfo.goodsImg }" />&nbsp;&nbsp;&nbsp;${carinfo.goodsName}</td>
		   <td class="tb2_td3" >${carinfo.goodsDiscrible }</td>
		   <td class="tb2_td5">
		     <input name="number" type="text" value="${carinfo.shopNum }" class="shopnum"
		     id="${carinfo.carId }" onblur="modifyNum(this);"
	         onfocus="getOldNum('${carinfo.shopNum }','${carinfo.goodsnumber }');"/>
		   </td>
		   <td class="tb2_td4" name="price">
		     ${carinfo.goodsPrice }
		   </td>
		   <td class="tb2_td4" class="tot">
		      ${carinfo.goodsPrice*carinfo.shopNum}
		   </td>
		   <td class=".tb2_td3 a">
		    <button id="shanchu1" onclick="removeById('${carinfo.carId }');">删除</button>
		   </td>
		</tr>	
		</c:forEach>
		
	</table>
	<br>
  <nav style="text-align: center" id="pageShow">
	<!--
        maxshowpageitem:设置当前页显示几个数字
        pagelistcount ：设置一共分多少页
    -->
    <div class="page" maxshowpageitem="5" pagelistcount="${carPage }"  id="page"></div>
  </nav>


	
	<table cellpadding="0" cellspacing="0" class="gwc_tb3">
		<tr>
			<td class="tb1_td1"><input type="button" value="清空购物车" onclick="clearChart();"/></td>
			<td class="tb3_td2">已选商品 <label id="shuliang" style="color:#ff5500;font-size:14px; font-weight:bold;"></label> 件</td>
			<td class="tb3_td3">合计(不含运费):<span>￥</span><span style=" color:#ff5500;"><label id="sumprice" style="color:#ff5500;font-size:14px; font-weight:bold;"></label></span></td>
			<td class="tb3_td4"><span id="jz1">结算</span><a href="javascript:payMoney();" style="display:none;"  class="jz2" id="jz2">结算</a></td>
		</tr>
	</table>
	<br>

</div>
</body>
</html>
<script type="text/javascript">

    //一进入此页面聚会触发下面的函数！
    var i=1;
    var GG = {
        "kk":function(mm){

            //此判断是让其第一次进来不触发
            if(i!=1){
                ajaxTable(mm);
            }
            i=0;
        }
    }
    
    $("#page").initPage(71,1,GG.kk);
    
    
    //异步分页代码
     function ajaxTable(num){
     	  $.ajax({
          type:'POST',
          url:'product.action?method=carPageManage',
          data:{
          	currentPage:num
          },
          success:function(response,status,xhr){ 
          	//对分页表格进行处理
          	carobj=eval('(' + response + ')');
          	var str="";
          	var bg;
          	for(var i=0;i<carobj.length;i++){
		    	bg = i%2==0?'white':'skyblue';
		    	str+="<tr bgcolor='"+bg+"'>"+
				   "<td class='tb2_td1' colspan='2'><input type='checkbox' name='checkbox' value='"+i+"' onclick='checkBoxWang(this);'></td>"+
				   "<td class='tb2_td2' class='.tb2_td2 img'><img style='width:60px;heigth:10px;' src='${pageContext.request.contextPath}/"+carobj[i].goodsImg+"' />&nbsp;&nbsp;&nbsp;"+carobj[i].goodsName+"</td>"+
				   "<td class='tb2_td3' >"+carobj[i].goodsDiscrible+"</td>"+
				   "<td class='tb2_td5'>"+
				     "<input name='number' type='text' value='"+carobj[i].shopNum+"'"+
				     "id="+carobj[i].carId+" onblur='modifyNum(this);'"+
			         "onfocus='getOldNum("+carobj[i].shopNum+","+carobj[i].goodsnumber+");'/>"+
				   "</td>"+
				   "<td class='tb2_td4' name='price'>"+carobj[i].goodsPrice+"</td>"+
				   "<td class='tb2_td4' class='tot'>"+
				      carobj[i].goodsPrice*carobj[i].shopNum+"</td>"+		   
				   "<td class='.tb2_td3 a'>"+
				    "<button id='shanchu1' onclick='removeById("+carobj[i].carId+");'>删除</button>"+
				   "</td></tr>";
    		}
          	$('#mydata').html(str);
          	//未选中不能结算样式！
	        $("#jz1").css("display", "block");
			$("#jz2").css("display", "none");
			document.getElementById("shuliang").innerHTML=0; 
	        document.getElementById("sumprice").innerHTML=0.0;
          }
      });
    }

    
</script>